package com.woniu.config;


import com.woniu.outlet.dao.MessagePoMapper;
import com.woniu.uitl.MessageStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * 回调函数
 */
@Component
@Slf4j
public class RabbitMqTemplate {

    @Autowired
    private MessagePoMapper messagePoMapper;

    @Bean
    public RabbitTemplate getRabbitmqTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate();
        template.setConnectionFactory(connectionFactory);
        //设置生产者到交换机回调函数
        template.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData cda, boolean b, String s) {
                //判断是否成功
                if (b){
                    //判断这条消息记录交换机路由到队列是否成功
                    com.woniu.outlet.po.MessagePo message = messagePoMapper.selectByPrimaryKey(Long.parseLong(cda.getId()));
                    if (!message.getStatus().equals(MessageStatus.ROUTE_ERROR.getStatus())){
                        //证明发送到队列成功
                        log.info("消息记录表发送到交换机成功");
                        //改消息记录表状态为已发送
                        message.setStatus(MessageStatus.SUCESS.getStatus());
                        messagePoMapper.updateByPrimaryKeySelective(message);
                    }
                    //失败了就人工干预
                }
            }
        });

        //设置交换机到队列回调函数
        template.setMandatory(true);
        template.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int i, String s, String s1, String s2) {
                log.info("交换机路由到队列失败了");
                com.woniu.outlet.po.MessagePo messPo = new com.woniu.outlet.po.MessagePo();
                //失败需要改消息记录表状态
                String id = message.getMessageProperties().getClusterId();
                messPo.setId(Long.parseLong(id));
                messPo.setStatus(MessageStatus.ROUTE_ERROR.getStatus());
                messagePoMapper.updateByPrimaryKeySelective(messPo);
            }
        });
        return template;
    }

}
